<template>
  <div class="paper-test-settings-page">
    <div class="settings-container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1 class="page-title">
          <el-icon class="title-icon"><Document /></el-icon>
          试卷测验
        </h1>
        <p class="page-subtitle">选择试卷开始测验，检验您的学习成果</p>
      </div>
      
      <!-- 主内容区域 -->
      <div class="main-content">
        <!-- 表单选择区域 -->
        <div class="settings-form">
          <el-form :model="testForm" label-width="90px" class="test-form">
            <el-form-item label="试卷名称">
              <el-input v-model="testForm.paperName" placeholder="请输入试卷名称或点击右侧选择" />
            </el-form-item>
            
            <!-- 试卷分值选择 -->
            <el-form-item label="试卷分值">
              <el-select 
                v-model="testForm.paperScoreId" 
                placeholder="请选择试卷分值配置" 
                clearable
              >
                <el-option
                  v-for="score in paperScoreList"
                  :key="score.id"
                  :label="`${score.examName} (${score.subject})`"
                  :value="score.id"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="startTest" :loading="loading" class="start-button">
                开始测验
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      
      <!-- 右侧浮动试卷列表 -->
      <div class="paper-list-drawer" :class="{ 'open': showPaperList }">
        <div class="drawer-toggle" @click="togglePaperList">
          <el-icon><Document /></el-icon>
        </div>
        <div class="drawer-content">
          <div class="drawer-header">
            <span>选择试卷</span>
            <el-icon class="close-icon" @click="togglePaperList"><Close /></el-icon>
          </div>
          <div class="drawer-body">
            <div v-if="paperListLoading" class="loading-tip">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>正在加载...</span>
            </div>
            <div v-else-if="paperList.length > 0" class="paper-list">
              <div 
                v-for="paper in paperList" 
                :key="paper.id" 
                class="paper-item"
                :class="{ 'active': selectedPaper?.id === paper.id }"
                @click="selectPaper(paper)"
              >
                <div class="paper-info">
                  <div class="paper-name">{{ paper.name }}</div>
                  <div class="paper-meta">
                    <span class="meta-item">
                      <el-icon><Timer /></el-icon>
                      {{ paper.totalDuration }}分钟
                    </span>
                    <span class="meta-item">
                      <el-icon><Document /></el-icon>
                      {{ getPaperQuestionCount(paper) }}题
                    </span>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="empty-tip">
              <el-icon><Document /></el-icon>
              <span>暂无试卷数据</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 遮罩层 -->
      <div v-if="showPaperList" class="drawer-overlay" @click="togglePaperList"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Document, Loading, Right, Timer, ArrowDown, Close, InfoFilled } from '@element-plus/icons-vue';
import * as paperApi from '@/api/paper';
import * as paperScoreApi from '@/api/paperScore';

const emit = defineEmits(['start-test']);

const router = useRouter();
const loading = ref(false);
const paperListLoading = ref(false);
const paperScoreListLoading = ref(false);

// 测验表单
const testForm = reactive({
  paperName: '',
  paperScoreId: null as number | null
});

// 试卷列表
const paperList = ref<any[]>([]);

// 试卷分值列表
const paperScoreList = ref<any[]>([]);

// 选中的试卷详情
const selectedPaper = ref<any>(null);

// 选中的试卷分值详情
const selectedPaperScore = ref<any>(null);

// 存储的答题进度
const savedProgress = ref<any>(null);

// 控制试卷列表展开/收起
const showPaperList = ref(false);

// 加载试卷列表
const loadPaperList = async () => {
  paperListLoading.value = true;
  try {
    const res: any = await paperApi.getAllPapers();
    if (res.code === 200 && res.data) {
      paperList.value = Array.isArray(res.data) ? res.data : [];
    } else {
      paperList.value = [];
    }
  } catch (error: any) {
    console.error('获取试卷列表失败:', error);
    paperList.value = [];
    ElMessage.error('获取试卷列表失败');
  } finally {
    paperListLoading.value = false;
  }
};

// 加载试卷分值列表
const loadPaperScoreList = async () => {
  paperScoreListLoading.value = true;
  try {
    const res: any = await paperScoreApi.getPaperScores({ page: 1, size: 100 });
    if (res.code === 200 && res.data) {
      paperScoreList.value = Array.isArray(res.data.list) ? res.data.list : [];
    } else {
      paperScoreList.value = [];
    }
  } catch (error: any) {
    console.error('获取试卷分值列表失败:', error);
    paperScoreList.value = [];
    ElMessage.error('获取试卷分值列表失败');
  } finally {
    paperScoreListLoading.value = false;
  }
};

// 获取试卷题目数量
const getPaperQuestionCount = (paper: any) => {
  // 这里可以调用API获取实际题目数量
  // 暂时返回一个默认值或从试卷对象中获取
  return paper.totalQuestions || 0;
};

// 选择试卷
const selectPaper = (paper: any) => {
  testForm.paperName = paper.name;
  selectedPaper.value = paper;
};

// 切换试卷列表展开/收起
const togglePaperList = () => {
  showPaperList.value = !showPaperList.value;
};

// 格式化日期时间
const formatDateTime = (dateString: string) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN');
};

const startTest = async () => {
  loading.value = true;
  try {
    // 验证表单
    if (!testForm.paperName) {
      ElMessage.error('请输入试卷名称');
      loading.value = false;
      return;
    }
    
    // 检查是否获取到了试卷详情（通过选择试卷的方式）
    if (!selectedPaper.value) {
      // 尝试通过试卷名称查找试卷
      await loadPaperList();
      const paper = paperList.value.find(p => p.name === testForm.paperName);
      if (paper) {
        selectedPaper.value = paper;
      } else {
        ElMessage.error('未找到指定的试卷');
        loading.value = false;
        return;
      }
    }
    
    const paper = selectedPaper.value;
    
    // 检查是否有保存的答题进度
    const progressKey = `paper_progress_${paper.id}`;
    const savedData = localStorage.getItem(progressKey);
    
    if (savedData) {
      try {
        const progress = JSON.parse(savedData);
        // 检查进度是否在24小时内
        const savedTime = new Date(progress.savedTime).getTime();
        const now = Date.now();
        const hoursDiff = (now - savedTime) / (1000 * 60 * 60);
        
        if (hoursDiff < 24) {
          // 询问用户是否继续上次答题
          await ElMessageBox.confirm(
            `检测到您有未完成的答题记录（已答 ${progress.answeredCount} 题），是否继续上次答题？`,
            '提示',
            {
              confirmButtonText: '继续答题',
              cancelButtonText: '重新开始',
              type: 'info'
            }
          ).then(() => {
            // 用户选择继续答题，跳转到练习页面并传递进度信息
            savedProgress.value = progress;
            navigateToPractice(paper, true);
            return;
          }).catch(() => {
            // 用户选择重新开始，清除进度
            localStorage.removeItem(progressKey);
            savedProgress.value = null;
            navigateToPractice(paper, false);
            return;
          });
          loading.value = false;
          return;
        } else {
          // 超过24小时，自动清除旧进度
          localStorage.removeItem(progressKey);
        }
      } catch (error) {
        console.error('解析答题进度失败:', error);
        localStorage.removeItem(progressKey);
      }
    }
    
    // 没有保存的进度，直接开始新的答题
    navigateToPractice(paper, false);
  } catch (error: any) {
    console.error('开始测验失败:', error);
    ElMessage.error('开始测验失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 导航到练习页面
const navigateToPractice = async (paper: any, continueProgress: boolean) => {
  try {
    
    // 检查试卷是否有题目
    const questionsRes: any = await paperApi.getPaperQuestions(paper.id);
    if (questionsRes.code !== 200 || !questionsRes.data || questionsRes.data.length === 0) {
      ElMessage.error('该试卷没有题目，无法开始测验');
      return;
    }
    
    // 如果选择了试卷分值配置，将其保存到sessionStorage
    if (testForm.paperScoreId && selectedPaperScore.value) {
      sessionStorage.setItem(`paperScore_${paper.id}`, JSON.stringify({
        paperScoreInfo: selectedPaperScore.value
      }));
      console.log('保存试卷分值配置到sessionStorage:', selectedPaperScore.value);
    } else {
      // 如果没有选择试卷分值，清除sessionStorage中的配置
      sessionStorage.removeItem(`paperScore_${paper.id}`);
      console.log('未选择试卷分值配置，清除sessionStorage');
    }
    
    // 发送开始测验事件
    emit('start-test', {
      paperId: paper.id,
      mode: 'sequential',
      showAnswers: false,
      paperScoreId: testForm.paperScoreId, // 传递试卷分值ID
      continueProgress: continueProgress // 传递是否继续答题的标识
    });
  } catch (error: any) {
    console.error('导航到练习页面失败:', error);
    ElMessage.error('开始测验失败，请稍后重试');
  }
};

// 监听试卷分值选择变化
watch(() => testForm.paperScoreId, (newVal) => {
  if (newVal) {
    selectedPaperScore.value = paperScoreList.value.find(score => score.id === newVal) || null;
  } else {
    selectedPaperScore.value = null;
  }
});

// 组件挂载时加载试卷列表和试卷分值列表
onMounted(() => {
  loadPaperList();
  loadPaperScoreList();
});
</script>

<style scoped>
.paper-test-settings-page {
  width: 100%;
  min-height: calc(100vh - 64px);
  background: #f5f7fa;
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding: 20px;
}

.settings-container {
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
  padding: 16px;
  box-sizing: border-box;
  position: relative;
  z-index: 1;
}

/* 页面标题样式 */
.page-header {
  text-align: center;
  margin-bottom: 24px;
  padding: 20px 0 0 0;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 12px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.title-icon {
  font-size: 32px;
  color: #409eff;
}

.page-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
  line-height: 1.5;
}

.main-content {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.settings-form {
  background: transparent;
  border-radius: 0;
  padding: 0;
  box-shadow: none;
  border: none;
  width: 100%;
}

.settings-form .test-form {
  padding: 0;
}

/* 右侧浮动试卷列表 */
.paper-list-drawer {
  position: fixed;
  right: 0;
  top: 64px;
  bottom: 0;
  width: 380px;
  background: white;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
  transform: translateX(100%);
  transition: transform 0.3s ease;
  z-index: 1001;
  display: flex;
  flex-direction: column;
}

.paper-list-drawer.open {
  transform: translateX(0);
}

/* 遮罩层 */
.drawer-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  backdrop-filter: blur(4px);
  cursor: pointer;
  transition: opacity 0.3s ease;
}

.drawer-toggle {
  position: absolute;
  left: -48px;
  top: 50%;
  transform: translateY(-50%);
  width: 48px;
  height: 48px;
  background: white;
  border-radius: 8px 0 0 8px;
  box-shadow: -2px 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.drawer-toggle:hover {
  background: #ecf5ff;
}

.drawer-toggle .el-icon {
  font-size: 24px;
  color: #409eff;
}

.drawer-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  font-weight: 600;
  font-size: 16px;
  color: #303133;
  flex-shrink: 0;
}

.close-icon {
  font-size: 18px;
  color: #909399;
  cursor: pointer;
  transition: color 0.3s ease;
}

.close-icon:hover {
  color: #409eff;
}

.drawer-body {
  flex: 1;
  overflow-y: auto;
  padding: 0;
}

.test-form {
  max-width: 100%;
}

/* 表单项样式优化 */
:deep(.el-form-item) {
  margin-bottom: 22px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
  font-size: 13px;
}

:deep(.el-select),
:deep(.el-input) {
  width: 100%;
}

:deep(.el-select .el-input__wrapper),
:deep(.el-input__wrapper) {
  border-radius: 4px;
  transition: all 0.3s ease;
  background: white;
}

.start-button {
  width: 100%;
  height: 40px;
  border-radius: 4px;
  font-size: 15px;
  font-weight: 500;
  margin-top: 4px;
}

/* 试卷列表样式 */
.paper-list {
  padding: 0;
}

.paper-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  margin: 0;
  background: white;
  border-radius: 0;
  cursor: pointer;
  transition: all 0.3s ease;
  border-bottom: 1px solid #f5f7fa;
}

.paper-item:last-child {
  border-bottom: none;
}

.paper-item:hover {
  background: #f5f7fa;
}

.paper-item.active {
  background: #ecf5ff;
  position: relative;
}

.paper-item.active::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 3px;
  background: #409eff;
}

.paper-info .paper-name {
  font-weight: 500;
  margin-bottom: 4px;
  color: #303133;
  font-size: 14px;
}

.paper-meta {
  display: flex;
  gap: 12px;
  align-items: center;
}

.meta-item {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 4px;
}

.meta-item .el-icon {
  font-size: 12px;
}

.select-icon {
  color: #c0c4cc;
  font-size: 16px;
  transition: all 0.3s ease;
  display: none;
}

.loading-tip,
.empty-tip {
  text-align: center;
  padding: 48px 20px;
  color: #909399;
  font-size: 14px;
}

.loading-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.loading-tip .el-icon {
  font-size: 24px;
}

.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.empty-tip .el-icon {
  font-size: 32px;
  color: #c0c4cc;
}

@media (max-width: 768px) {
  .paper-test-settings-page {
    padding: 16px;
  }
  
  .page-header {
    margin-bottom: 20px;
    padding: 12px 0 0 0;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .title-icon {
    font-size: 28px;
  }
  
  .page-subtitle {
    font-size: 13px;
  }
  
  .paper-list-drawer {
    width: 100%;
  }
  
  .drawer-toggle {
    left: -40px;
    width: 40px;
    height: 40px;
  }
  
  .drawer-toggle .el-icon {
    font-size: 20px;
  }
}
</style>